'use client'

import { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { 
  MessageSquare, 
  Plus, 
  Search, 
  MoreVertical, 
  Pin, 
  PinOff, 
  Edit2, 
  Trash2,
  X,
  ChevronLeft,
  ChevronRight
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { 
  DropdownMenu, 
  DropdownMenuContent, 
  DropdownMenuItem, 
  DropdownMenuTrigger 
} from '@/components/ui/dropdown-menu'
import { Badge } from '@/components/ui/badge'
import { useToast } from '@/hooks/use-toast'
import {
  getChatSessions,
  updateChatSession,
  deleteChatSession
} from '@/apis/client/chat'
import { ChatSession } from '@/types/chat'

interface ChatSessionSidebarProps {
  currentChatId?: string | null
  onSessionSelect: (chatId: string, contentId?: string) => void
  onNewSession: () => void
  isCollapsed?: boolean
  onToggleCollapse?: () => void
}

export function ChatSessionSidebar({ 
  currentChatId, 
  onSessionSelect, 
  onNewSession,
  isCollapsed = false,
  onToggleCollapse
}: ChatSessionSidebarProps) {
  const [searchQuery, setSearchQuery] = useState('')
  const [editingSessionId, setEditingSessionId] = useState<string | null>(null)
  const [editingTitle, setEditingTitle] = useState('')
  const { toast } = useToast()
  const queryClient = useQueryClient()

  // 获取聊天会话列表
  const { data: sessions = [], isLoading, refetch } = useQuery({
    queryKey: ['chatSessions', searchQuery],
    queryFn: () => getChatSessions({ title: searchQuery }),
    refetchOnWindowFocus: false,
  })

  // 创建新会话（现在只是调用父组件回调）
  // const createSessionMutation = useMutation({
  //   mutationFn: createChatSession,
  //   onSuccess: (newSession) => {
  //     queryClient.invalidateQueries({ queryKey: ['chatSessions'] })
  //     onNewSession(newSession.chatId)
  //     toast({
  //       title: '创建成功',
  //       description: '新的聊天会话已创建',
  //     })
  //   },
  //   onError: (error) => {
  //     toast({
  //       title: '创建失败',
  //       description: error instanceof Error ? error.message : '创建聊天会话失败',
  //       variant: 'destructive',
  //     })
  //   },
  // })

  // 更新会话
  const updateSessionMutation = useMutation({
    mutationFn: ({ chatId, updates }: { chatId: string; updates: any }) => 
      updateChatSession(chatId, updates.title),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['chatSessions'] })
      setEditingSessionId(null)
      toast({
        title: '更新成功',
        description: '聊天会话已更新',
      })
    },
    onError: (error) => {
      toast({
        title: '更新失败',
        description: error instanceof Error ? error.message : '更新聊天会话失败',
        variant: 'destructive',
      })
    },
  })

  // 删除会话
  const deleteSessionMutation = useMutation({
    mutationFn: deleteChatSession,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['chatSessions'] })
      toast({
        title: '删除成功',
        description: '聊天会话已删除',
      })
    },
    onError: (error) => {
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '删除聊天会话失败',
        variant: 'destructive',
      })
    },
  })

  const handleCreateSession = () => {
    onNewSession()
  }

  const handleTogglePin = (session: ChatSession) => {
    // updateSessionMutation.mutate({
    //   chatId: session.chatId,
    //   updates: { isPinned: !session.isPinned }
    // })
  }

  const handleStartEdit = (session: ChatSession) => {
    setEditingSessionId(session.id)
    setEditingTitle(session.title)
  }

  const handleSaveEdit = (chatId: string) => {
    if (editingTitle.trim()) {
      updateSessionMutation.mutate({
        chatId,
        updates: { title: editingTitle.trim() }
      })
    } else {
      setEditingSessionId(null)
    }
  }

  const handleCancelEdit = () => {
    setEditingSessionId(null)
    setEditingTitle('')
  }

  const handleDeleteSession = (chatId: string) => {
    if (confirm('确定要删除这个聊天会话吗？此操作不可恢复。')) {
      deleteSessionMutation.mutate(chatId)
    }
  }

  const formatTime = (dateString: string) => {
    const date = new Date(dateString)
    const now = new Date()
    const diffInHours = (now.getTime() - date.getTime()) / (1000 * 60 * 60)

    if (diffInHours < 24) {
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    } else if (diffInHours < 24 * 7) {
      return date.toLocaleDateString('zh-CN', { 
        month: 'short', 
        day: 'numeric' 
      })
    } else {
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: 'short', 
        day: 'numeric' 
      })
    }
  }

  if (isCollapsed) {
    return (
      <div className="w-16 bg-white border-r border-gray-200 flex flex-col items-center py-4 space-y-4">
        <Button
          variant="ghost"
          size="sm"
          onClick={onToggleCollapse}
          className="p-2"
        >
          <ChevronRight className="w-4 h-4" />
        </Button>
        
        <Button
          variant="ghost"
          size="sm"
          onClick={handleCreateSession}
          className="p-2"
        >
          <Plus className="w-4 h-4" />
        </Button>

        <div className="flex-1 flex flex-col space-y-2 w-full px-2">
          {sessions.slice(0, 5).map((session) => (
            <Button
              key={session.id}
              variant={currentChatId === session.chatId ? "default" : "ghost"}
              size="sm"
              onClick={() => onSessionSelect(session.chatId, session.contentId)}
              className="p-2 w-full"
            >
              <MessageSquare className="w-4 h-4" />
            </Button>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="w-80 bg-white border-r border-gray-200 flex flex-col h-full shadow-lg md:shadow-none">
      {/* 头部 */}
      <div className="p-4 border-b border-gray-200">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-gray-900">聊天记录</h2>
          <div className="flex items-center space-x-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={handleCreateSession}
            >
              <Plus className="w-4 h-4" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={onToggleCollapse}
            >
              <ChevronLeft className="w-4 h-4" />
            </Button>
          </div>
        </div>

        {/* 搜索框 */}
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <Input
            placeholder="搜索聊天记录..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>
      </div>

      {/* 会话列表 */}
      <div className="flex-1 overflow-y-auto">
        {isLoading ? (
          <div className="p-4 text-center text-gray-500">
            加载中...
          </div>
        ) : sessions.length === 0 ? (
          <div className="p-4 text-center text-gray-500">
            {searchQuery ? '没有找到相关聊天记录' : '还没有聊天记录'}
          </div>
        ) : (
          <div className="space-y-1 p-2">
            {sessions.map((session) => (
              <div
                key={session.id}
                className={`group relative p-3 rounded-lg cursor-pointer transition-colors ${
                  currentChatId === session.chatId
                    ? 'bg-blue-50 border border-blue-200'
                    : 'hover:bg-gray-50'
                }`}
                onClick={() => onSessionSelect(session.chatId, session.contentId)}
              >
                <div className="flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    {editingSessionId === session.id ? (
                      <div className="flex items-center space-x-2">
                        <Input
                          value={editingTitle}
                          onChange={(e) => setEditingTitle(e.target.value)}
                          onKeyDown={(e) => {
                            if (e.key === 'Enter') {
                              handleSaveEdit(session.chatId)
                            } else if (e.key === 'Escape') {
                              handleCancelEdit()
                            }
                          }}
                          className="text-sm"
                          autoFocus
                        />
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={(e) => {
                            e.stopPropagation()
                            handleCancelEdit()
                          }}
                        >
                          <X className="w-3 h-3" />
                        </Button>
                      </div>
                    ) : (
                      <>
                        <div className="flex items-center space-x-2">
                          <h3 className="text-sm font-medium text-gray-900 truncate">
                            {session.title}
                          </h3>
                          {/* {session.isPinned && (
                            <Pin className="w-3 h-3 text-blue-500 flex-shrink-0" />
                          )} */}
                        </div>
                        {session.lastMessage && (
                          <p className="text-xs text-gray-500 mt-1 truncate">
                            {session.lastMessage}
                          </p>
                        )}
                        <div className="flex items-center justify-between mt-2">
                          <span className="text-xs text-gray-400">
                            {formatTime(session.updatedAt)}
                          </span>
                          {session.messageCount && (
                            <Badge variant="secondary" className="text-xs">
                              {session.messageCount}条
                            </Badge>
                          )}
                        </div>
                      </>
                    )}
                  </div>

                  {editingSessionId !== session.id && (
                    <DropdownMenu>
                      <DropdownMenuTrigger >
                        <Button
                          variant="ghost"
                          size="sm"
                          className="opacity-0 group-hover:opacity-100 transition-opacity"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <MoreVertical className="w-4 h-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={() => handleStartEdit(session)}>
                          <Edit2 className="w-4 h-4 mr-2" />
                          重命名
                        </DropdownMenuItem>
                        {/* <DropdownMenuItem onClick={() => handleTogglePin(session)}>
                          {session.isPinned ? (
                            <>
                              <PinOff className="w-4 h-4 mr-2" />
                              取消置顶
                            </>
                          ) : (
                            <>
                              <Pin className="w-4 h-4 mr-2" />
                              置顶
                            </>
                          )}
                        </DropdownMenuItem> */}
                        <DropdownMenuItem 
                          onClick={() => handleDeleteSession(session.chatId)}
                          className="text-red-600"
                        >
                          <Trash2 className="w-4 h-4 mr-2" />
                          删除
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
